/*
 * @Author: shawnxiao
 * @Date: 2021-02-16 18:30:39
 * @LastEditTime: 2021-12-17 14:42:05
 * @FilePath: /vite2-vue3-ts-antd/src/common/directives/drag.ts
 */
const dragDirective = {
  mounted(el: any) {
    // 要实现拖拽，要给元素添加绝对定位
    el.style.position = 'absolute'
    el.onmousedown = function (e: any) {
      // 用元素距离视窗的X、Y坐标，减去el元素最近的相对定位父元素的left、top值
      const sX = e.clientX - el.offsetLeft
      const sY = e.clientY - el.offsetTop
      document.onmousemove = function (e) {
        const eX = e.clientX - sX
        const eY = e.clientY - sY
        el.style.left = `${eX}px`
        el.style.top = `${eY}px`
      }
      document.onmouseup = function () {
        // 清除onmousemove事件
        document.onmousemove = null
      }
    }
  },
  updated(el: any, binding: any) {
    console.log(el, binding)
  }
}

export function setupDragDirective(app: any) {
  app.directive('drag', dragDirective)
}

export default dragDirective
